﻿using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TongTongMall.Dependecy;

namespace TongTongMall.Redis.Cache.Lock
{
    public class RedisLockWrapper : IDisposable
    {
        private RedisLockInstance LockInstance;

        private RedisLock Lock { get; set; }

        private string Keys { get; set; }

        private TimeSpan? LockDisposeTimeSpan { get; set; }
        public IRedisCacheDatabaseProvider RedisCacheDatabaseProvider
        {
            get
            {
                return IocManager.Instance.Resolve<IRedisCacheDatabaseProvider>();
            }
        }

        public RedisLockWrapper(string resource, TimeSpan? validity = null)
        {
            Keys = resource;
            LockDisposeTimeSpan = validity;
            //创建一个锁的实例
            Lock = new RedisLock(RedisCacheDatabaseProvider.ConnectionMultiplexer);
        }

        public bool IsLockPremission
        {
            get
            {
                return Lock.Lock(Keys, LockDisposeTimeSpan ?? TimeSpan.FromSeconds(3), out LockInstance);
            }
        }

        public void Dispose()
        {
            if (LockInstance != null)
            {
                Lock.Unlock(LockInstance);
            }
        }
    }
}
